<?php

class IssueController extends Controller
{
  public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the register page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xCCCCCC,
				'minLength'=>7
			),
		);
	}
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', 
				'actions'=>array('submit','captcha','check','assign'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
 	/**
 	* Check page. 
 	*/
	public function actionCheck()
	{
		$model=new Issue('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Issue']))
			$model->attributes=$_GET['Issue'];

		$this->render('check',array(
			'model'=>$model,
		));
	} 
		
	
	/**
	 * Submit Issue.
	 */
	public function actionSubmit()
	{
		$model=new Issue;
		$balance = UserBalance::model()->getBalance(Yii::app()->user->id);
		if($balance<10000)
		{
			//print json_encode(array('result'=>array('error'=>'Số dư tài khoản của bạn không đủ để thực hiện thao tác này. Vui lòng nạp tiền để tiếp tục sử dụng dịch vụ. Cám ơn')));
			Yii::app()->user->setFlash("no-balance","Số dư tài khoản của bạn không đủ để thực hiện thao tác này. Vui lòng nạp tiền để tiếp tục sử dụng dịch vụ. Cám ơn.");
		}
		
		if(isset($_POST['Issue']))
		{
			$model->attributes=$_POST['Issue'];	
			$model->userID = Yii::app()->user->id;
			$model->gradeID = $_POST['Issue']['gradeID'];
			$model->subjectID = $_POST['Issue']['subjectID'];
			$model->quantity_object = $_POST['Issue']['quantity_object'];
			$model->content = $_POST['Issue']['content'];
			
			//Khu khoang trang trong content, truong hop chi go khoang trang ko
			$str = str_replace('&nbsp;', '', $model->content);
      $str = trim($str);
      $str = str_replace(' ', '', strip_tags($str, '<img>'));
      
      // Get image objects
		  $imgs = CUploadedFile::getInstances($model,"image"); 
			$errors = array();
			$list_file = array();
			
			if(!empty($imgs)) {
				foreach ($imgs as $key=>$img) {
					$model->image = CUploadedFile::getInstance($model,"image[$key]");
					$list_file[] = $model->image; 
			    if(!$model->validate()) {
			    	$errors[] = $model->getErrors("image");
			    }
				}
			}		  
			
			//validate Issue model
			$validate1 = $model->validate(array('gradeID','subjectID','quantity_object','captcha'));
			
			if($validate1 && (!empty($str) || (empty($errors) && !empty($list_file)))) {	   

				//Lay gia tien cua mot bai giai dua vao muc do khan can cua issue;
				$p = Price::model()->getPrice($model->emergency);
				if($p==0)
				{
					$p =10000;
				}				
				
				//Kiem tra so luong bai va so du tai khoan
				$price = $model->quantity_object * $p;
				
				if ($balance<$price)
				{
			 		print json_encode(array('result'=>array('error'=>'Số dư tài khoản của bạn không đủ để thực hiện thao tác này. Vui lòng nạp tiền để tiếp tục sử dụng dịch vụ. Cám ơn.')));
			 		die;
				}
				
				// get available checker  
				$checkerID = $model->getChecker();
				if($checkerID!=0) {
					$model->status = 21;
					$model->checker = $checkerID; 
					$user_status = UserStatus::model()->findByAttributes(array('userID'=>$checkerID));
					if(!empty($user_status))
					{
						$user_status->statusID = 3;
						$user_status->update();
					}
									
					// estimate time 1 (normal)					
					$model->estimate_idle_time = Issue::model()->estimateTime($model->emergency);
				}		
				else {
					
					// get checker 2 and estimate time 2 (busy time)
					$model->estimate_idle_time = Issue::model()->estimateTime($model->emergency);;
					$model->status = 20;
				}		
				
				// count expire time for issue/answer/question
				$expire = time()+ ($model->estimate_idle_time - 5)*60;
				$model->notify_date = $expire;
						
				if($model->save(false)) {
					if(!empty($imgs)) {
						foreach ($imgs as $img) {
							$file=new File();
							$file->filename = $img->getName();
				    	$file->filesaved = encodeFilename(time().'_'.$img->getName());
				    	$file->filetype = 'image';
				    	$file->folder = 'issues';
				    	$file->save(false);
				    	$img->saveAs('upload/issues/'.$file->filesaved);
							$fileID =  $file->ID;
							$file_issue = new FileIssue();
							$file_issue->issueID = $model->ID;
							$file_issue->fileID = $file->ID; 
							$file_issue->save(false);	
						}
					}
					
					for ($i = 0; $i < $model->quantity_object; $i++) {
						
								// Generate new answer records.
								$answer = new Answer();
								$answer->issueID=$model->ID;
								$answer->thread_number =$i+1;
								//$answer->expire_resolve_time = $expire - ($model->estimate_idle_time*2/3)*60;;
								$answer->expire_resolve_time = $expire - ($model->estimate_idle_time*40);
								$answer->expire_edit_time = $expire;
								$answer->save(false);
								
								// Generate new question
								$question = new Question();
								$question->issueID = $model->ID;
								$question->thread_number = $i+1;
								$question->expire_time = $expire;
								$question->save(false);
							}
				}	
				
				
				// Ghi log userPayment, trừ tiền tài khoản chính
				UserBalance::model()->addUserPayment(Yii::app()->user->id, 2, $price);
				
				//Trừ tiền trong UserBalance và ghi log userpayment
				$userbalance = UserBalance::model()->findByAttributes(array('userID'=>Yii::app()->user->id));    
			  if(!empty($userbalance))
				{
					//$userbalance->balance = $userbalance->balance - $price;
					
					$userbalance->balance = UserBalance::model()->checkBalance(Yii::app()->user->id, 1, 2);
					$userbalance->save(false);
				}		 
				
				
			/*	
		    $userpayment = new UserPayment();
		    //$model->money = 10000;		   		   
		    $userpayment->userID = Yii::app()->user->id;
		    $userpayment->money = $price;
		    $userpayment->status = 2; // out-balance
		    $userpayment->description = 'Tiền giải bài tập '.$price.' VND';
		    $userpayment->datetime = time();
		    $userpayment->save(false);			
				*/
				
				//validate the upload file				
				//save file to the upload path				
				
				//Yii::app()->user->setFlash('success',"Submit thanh cong");
				//$this->refresh();
				print json_encode(array('result'=>array('success'=>'Submit thành công')));
			}	
			else {
			  $output = getErrors($model);
			 
				if(empty($list_file) && empty($str)) {
					//$model->addError('image', 'Nhập nội dung hoặc chọn File');
					$output .= 'Nhập nội dung hoặc chọn File<br>';
				}
				if(!empty($errors)) {
					foreach ($errors as $err) {
						foreach ($err as $val) {
						  $output .= $val.'<br>';
							//$model->addError('image', $val);
						}
					}
				}
				print json_encode(array('result'=>array('error'=>$output)));
			}
			die;
		}
		$this->render('submit',array(
			'model'=>$model,
		));
	}
	
	
	/**
	 *  
	 */
	public function actionAssign()
	{
		$model=new Issue('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Issue']))
			$model->attributes=$_GET['Issue'];

		$this->render('assign',array(
			'model'=>$model,
		));
	}		
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Issue::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
}
